<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>通知测试页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .section {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .status {
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
        }
        .connected {
            background-color: #d4edda;
            color: #155724;
        }
        .disconnected {
            background-color: #f8d7da;
            color: #721c24;
        }
        .notification {
            padding: 10px;
            margin: 5px 0;
            background-color: #f8f9fa;
            border-left: 4px solid #007bff;
        }
        .settings-group {
            margin: 10px 0;
        }
        button {
            padding: 8px 15px;
            margin: 5px;
            cursor: pointer;
        }
        input[type="text"] {
            padding: 8px;
            margin: 5px;
            width: 200px;
        }
        .warning {
            background-color: #fff3cd;
            color: #856404;
            padding: 10px;
            margin-bottom: 15px;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div class="warning">
        <strong>重要提示：</strong> 请从 <a href="http://localhost:5173">http://localhost:5173</a> 访问此页面，或将此页面复制到前端项目中运行，以避免CORS问题。
    </div>

    <div class="section">
        <h2>用户登录</h2>
        <div>
            <input type="text" id="userId" placeholder="用户ID">
            <input type="text" id="token" placeholder="Token" style="width: 300px;">
            <button onclick="login()">登录</button>
        </div>
    </div>

    <div class="section">
        <h2>WebSocket状态</h2>
        <div id="wsStatus" class="status disconnected">未连接</div>
    </div>

    <div class="section">
        <h2>通知设置</h2>
        <div class="settings-group">
            <label>
                <input type="checkbox" id="messageNotification" checked>
                接收消息通知
            </label>
        </div>
        <div class="settings-group">
            <label>
                <input type="checkbox" id="favoriteNotification" checked>
                接收收藏通知
            </label>
        </div>
        <div class="settings-group">
            <label>
                <input type="checkbox" id="transactionNotification" checked>
                接收交易通知
            </label>
        </div>
        <div class="settings-group">
            <label>
                <input type="checkbox" id="systemNotification" checked>
                接收系统通知
            </label>
        </div>
        <button onclick="updateSettings()">保存设置</button>
        <button onclick="getCurrentSettings()">获取当前设置</button>
    </div>

    <div class="section">
        <h2>通知列表</h2>
        <div id="notifications"></div>
    </div>

    <script>
        // 检查当前访问的域名
        const currentHost = window.location.host;
        const allowedHost = 'localhost:5173';
        if (currentHost !== allowedHost) {
            document.querySelector('.warning').style.display = 'block';
        } else {
            document.querySelector('.warning').style.display = 'none';
        }

        const API_BASE_URL = 'http://localhost:8080/api';
        const WS_BASE_URL = 'ws://localhost:8080';
        let ws = null;
        let currentUserId = null;
        let retryCount = 0;
        const MAX_RETRIES = 3;

        // WebSocket连接
        function connectWebSocket() {
            if (ws) {
                ws.close();
            }

            const token = document.getElementById('token').value;
            if (!token) {
                alert('请先登录');
                return;
            }

            try {
                // 使用完整格式的token
                const tokenWithBearer = token.startsWith('Bearer ') ? token : `Bearer ${token}`;
                
                // 添加token到WebSocket连接URL
                ws = new WebSocket(`${WS_BASE_URL}/ws/chat`);
                
                ws.onopen = (event) => {
                    console.log('WebSocket连接已打开');
                    
                    // 连接后发送认证消息
                    const authMessage = {
                        type: 'AUTH',
                        userId: currentUserId,
                        token: tokenWithBearer
                    };
                    ws.send(JSON.stringify(authMessage));
                    
                    document.getElementById('wsStatus').className = 'status connected';
                    document.getElementById('wsStatus').textContent = '已连接';
                    retryCount = 0; // 重置重试计数
                };

                ws.onclose = (event) => {
                    document.getElementById('wsStatus').className = 'status disconnected';
                    document.getElementById('wsStatus').textContent = '已断开';
                    console.log('WebSocket连接已关闭', event);
                    
                    // 如果不是正常关闭，尝试重连
                    if (event.code !== 1000 && retryCount < MAX_RETRIES) {
                        retryCount++;
                        setTimeout(() => {
                            console.log(`尝试重新连接 (${retryCount}/${MAX_RETRIES})`);
                            connectWebSocket();
                        }, 3000);
                    }
                };

                ws.onerror = (error) => {
                    console.error('WebSocket错误:', error);
                    document.getElementById('wsStatus').className = 'status disconnected';
                    document.getElementById('wsStatus').textContent = '连接错误';
                };

                ws.onmessage = (event) => {
                    try {
                        console.log('收到消息:', event.data);
                        const notification = JSON.parse(event.data);
                        addNotification(notification);
                    } catch (error) {
                        console.error('解析消息失败:', error);
                    }
                };
            } catch (error) {
                console.error('创建WebSocket连接失败:', error);
                alert('创建WebSocket连接失败: ' + error.message);
            }
        }

        // 用户登录
        function login() {
            const userId = document.getElementById('userId').value;
            const token = document.getElementById('token').value;

            if (!userId || !token) {
                alert('请输入用户ID和Token');
                return;
            }

            currentUserId = userId;
            connectWebSocket();
            getCurrentSettings();
        }

        // 更新通知设置
        function updateSettings() {
            const settings = {
                notification_messages: document.getElementById('messageNotification').checked ? 1 : 0,
                notification_favorites: document.getElementById('favoriteNotification').checked ? 1 : 0,
                notification_transactions: document.getElementById('transactionNotification').checked ? 1 : 0,
                notification_system: document.getElementById('systemNotification').checked ? 1 : 0
            };

            // 使用本地代理或直接请求
            const token = document.getElementById('token').value;
            const tokenWithBearer = token.startsWith('Bearer ') ? token : `Bearer ${token}`;
            
            const options = {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': tokenWithBearer,
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify(settings)
            };
            
            // 添加AJAX请求调试信息
            console.log('发送设置更新请求:', options);
            
            fetch(`${API_BASE_URL}/user/settings`, options)
            .then(response => {
                console.log('收到响应:', response);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('响应数据:', data);
                if (data.code === 200) {
                    alert('设置更新成功');
                } else {
                    alert('设置更新失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('设置更新失败: ' + error.message);
            });
        }

        // 获取当前设置
        function getCurrentSettings() {
            const token = document.getElementById('token').value;
            const tokenWithBearer = token.startsWith('Bearer ') ? token : `Bearer ${token}`;
            
            const options = {
                headers: {
                    'Authorization': tokenWithBearer,
                    'X-Requested-With': 'XMLHttpRequest'
                }
            };
            
            console.log('发送获取设置请求:', options);
            
            fetch(`${API_BASE_URL}/user/settings`, options)
            .then(response => {
                console.log('收到响应:', response);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('响应数据:', data);
                if (data.code === 200) {
                    const settings = data.data;
                    document.getElementById('messageNotification').checked = settings.notification_messages === 1;
                    document.getElementById('favoriteNotification').checked = settings.notification_favorites === 1;
                    document.getElementById('transactionNotification').checked = settings.notification_transactions === 1;
                    document.getElementById('systemNotification').checked = settings.notification_system === 1;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('获取设置失败: ' + error.message);
            });
        }

        // 添加通知到列表
        function addNotification(notification) {
            const notificationsDiv = document.getElementById('notifications');
            const notificationDiv = document.createElement('div');
            notificationDiv.className = 'notification';
            
            let content = '';
            switch (notification.type) {
                case 'message':
                    content = `新消息: ${notification.content}`;
                    break;
                case 'favorite':
                    content = `收藏通知: ${notification.content}`;
                    break;
                case 'transaction':
                    content = `交易通知: ${notification.content}`;
                    break;
                case 'system':
                    content = `系统通知: ${notification.content}`;
                    break;
                default:
                    content = `通知: ${notification.content}`;
                    break;
            }
            
            const timestamp = notification.created_at 
                ? new Date(notification.created_at).toLocaleString()
                : new Date().toLocaleString();
            
            notificationDiv.innerHTML = `
                <div>${content}</div>
                <div style="font-size: 0.8em; color: #666;">${timestamp}</div>
            `;
            
            notificationsDiv.insertBefore(notificationDiv, notificationsDiv.firstChild);
        }
    </script>
</body>
</html> 